<template>
  <div class="page-container">
    <!-- 核心：van-list 区域（自动占满剩余空间并滚动） -->
    <div class="list-wrapper">
      <van-list
        :offset="500"
        ref="scrollRef"
        class="scrollable-list"
        v-model:loading="loading"
        :finished="!hasMore"
        finished-text="--- No more ---"
        @load="fetchProducts">
        <Swiper />
        <ProductList class="mt-[16px]" :products="products" />
        <template #loading>
          <div class="custom-loading pt-[20px] pb-[20px]">
            <van-loading type="spinner" color="#1989fa" size="20" />
          </div>
        </template>
        <template #finished>
          <NoMore :class="isShowLoginButton && 'mb-[46px]'" />
        </template>
      </van-list>
    </div>
    <LoginButton v-if="isShowLoginButton" />
  </div>
</template>

<script setup lang="ts">
  import Swiper from '@/views/home/components/swiper.vue';
  import ProductList from '@/components/ProductList.vue';
  import LoginButton from '@/components/LoginButton.vue';
  import NoMore from '@/components/NoMore.vue';

  import { throttle } from 'lodash';
  import {
    onMounted,
    ref,
    onUnmounted,
    computed,
    onActivated,
    onDeactivated,
    nextTick,
    watch,
  } from 'vue';
  import { FeedsAPI, type FeedItem, type FeedsParams } from '@/api/feeds';
  import request from '@/utils/request';
  import { useRetryEventBus } from '@/utils/retryEventBus';
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
  import { useUserStore } from '@/store/user';
  import { bus, useBus } from '@/utils/bus';
  import { UserAPI } from '@/api/user';

  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();
  const scrollRef = ref<any>(null);
  const isShowLoginButton = ref<boolean>(false);

  // 定义组件名称，用于keep-alive缓存
  defineOptions({
    name: 'HomePage',
  });

  const userInfo = computed(() => userStore.user);
  const isLoggedIn = computed(() => userStore.isAuthenticated);
  const products = ref<FeedItem[]>([]); // 列表数据
  const loading = ref(false);
  const hasMore = ref(true);
  // 分页相关数据
  const start = ref(0);
  const size = ref(30);
  const savedScrollPosition = ref(0);

  watch(
    // 监听全局当前路由的响应式对象
    () => router.currentRoute.value,
    (newRoute) => {},
    { immediate: true } // 初始化时立即执行一次，获取当前路由
  );

  // 监听用户登录状态变化
  watch(isLoggedIn, (newValue, oldValue) => {
    console.log('用户登录状态变化:', { newValue, oldValue });
    if (newValue !== oldValue) {
      console.log('登录状态变化，重新加载数据');
      start.value = 0;
      products.value = [];
      hasMore.value = true;
      loading.value = true;
      fetchProducts();
    }
  });

  onMounted(() => {
    nextTick(addEvent);
  });

  onUnmounted(() => {
    removeEvent();
  });

  onActivated(() => {
    restoreScrollPosition();
  });

  // 恢复滚动位置（无动画）
  const restoreScrollPosition = () => {
    if (savedScrollPosition.value > 0 && scrollRef.value) {
      scrollRef.value.$el.scrollTop = savedScrollPosition.value;
    }
  };

  const addEvent = () => {
    const listDom: any = scrollRef.value?.$el;
    if (listDom) {
      listDom.addEventListener('scroll', throttleHandleScroll);
    }
  };

  const removeEvent = () => {
    const listDom: any = scrollRef.value?.$el;
    if (listDom) {
      listDom.removeEventListener('scroll', throttleHandleScroll);
    }
  };

  // 展示登录按钮
  const handleScroll = (e: any) => {
    const scrollTop = e.target.scrollTop; // 已滚动距离（顶部）
    const screenHeight = window.screen.height;
    savedScrollPosition.value = e.target.scrollTop;
    isShowLoginButton.value = scrollTop > screenHeight;
  };

  const throttleHandleScroll = throttle(handleScroll, 300);

  // 实际的数据获取函数
  const fetchProducts = async (isLoadMore = false) => {
    try {
      const params: FeedsParams = {
        start: start.value,
        size: size.value,
        category_id: 1,
      };
      // 未登录用户限制数据量，不启用分页
      console.log('isLoggedIn', isLoggedIn.value);
      if (!isLoggedIn.value) {
        params.size = 20; // 未登录用户只加载20条数据
        console.log('未登录用户，限制数据量:', params.size);
      }
      // 根据是否登录选择不同的API
      let apiUrl = '/feeds/homepage';
      if (isLoggedIn.value && userInfo.value) {
        apiUrl = '/feeds/feature';
        console.log('用户已登录，使用正式数据接口:', apiUrl);
      }
      const response = await request.post(apiUrl, params);
      if (response.code == 200 && response.data.feeds && response.data.feeds.length > 0) {
        products.value = [...products.value, ...response.data.feeds];
      }
      start.value = response.data.next_start;
      // 检查是否还有更多数据
      // 未登录用户禁用分页
      if (!isLoggedIn.value || !userInfo.value) {
        hasMore.value = false; // 未登录用户禁用分页
      } else {
        hasMore.value = response.data.has_more;
      }
      loading.value = false;
      console.log('加载产品数据成功:', response);
    } catch (error) {
      console.error('加载产品数据失败:', error);
    } finally {
      // loading.value = false;
    }
  };
</script>

<style scoped lang="scss">
  .page-container {
    height: 100vh;
    height: 100dvh;
    padding-top: 56px;
    display: flex;
    flex-direction: column; /* 垂直布局 */
    overflow: hidden; /* 禁止页面整体滚动 */
    background: #f8f8f8;
  }

  /* 3. 列表容器：自动占据剩余空间 */
  .list-wrapper {
    flex: 1; /* 核心：分配顶部之外的所有剩余高度 */
    overflow: hidden; /* 裁剪超出部分，避免影响页面 */
    background: #f5f5f5; /* 列表背景色 */
    padding: 0 8px;
  }

  /* 4. 让 van-list 自身可滚动 */
  .scrollable-list {
    padding-top: 8px;
    height: 100%; /* 占满父容器高度 */
    overflow-y: auto; /* 允许内部纵向滚动 */
  }
  .scrollable-list::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    background-color: transparent;
    color: transparent;
  }
</style>
